/*
 * Created on Jun 24, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.peterrussell.contractionTimer;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Ticker;

import org.peterrussell.contractionTimer.model.ContractionTimeDAO;
import org.peterrussell.contractionTimer.model.ContractionTimeDTO;


/**
 * @author peterr
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Controller {


	public int NONE = 0;
	public int CONTRACTION = 1;
	public int BETWEEN_CONTRACTION = 2;
	
    private Ticker ticker;
    private int isTiming = NONE;
    private UIController uicontroller;
	private long time = 0;
	private long currContractionTime = 0;
	private long currBetweenTime = 0;
	private TimeMover clock = new TimeMover();
	private Timer timer = new Timer();
	private ContractionTimeDTO dto;
	/**
	 * 
	 */
	public Controller() {
		uicontroller = new LCDController();
		timer.schedule(clock, 1000, 1000);
	}
	
	public void start() {
		uicontroller.start();
		dto = ContractionTimeDAO.getDTO();
	}
	
	public void exit() {
		uicontroller.exit();
	}
	
	public void startTimer() {
		if (isTiming == CONTRACTION) {
			isTiming = BETWEEN_CONTRACTION;
			uicontroller.startBetweenContractionTimer();
		} else {
			isTiming = CONTRACTION;
			uicontroller.startContractionTimer();
		}
	}
	
	public void stopTimer() {
		if (isTiming == CONTRACTION) {
			startTimer();
			uicontroller.stopContractionTimer();
		} else {
			isTiming = CONTRACTION;
			ContractionTimeDAO.setDTO(dto);
			uicontroller.stopBetweenContractionTimer();
			dto.clear();
			uicontroller.refreshContractionTimer(dto);
			uicontroller.refreshBetweenContractionTimer(dto);
		}
	}
	
	public void advanceTime() {
	 	if (isTiming == CONTRACTION) {
	 	    dto.setContractionTime(dto.getContractionTime()+1000);
	 	    uicontroller.refreshContractionTimer(dto);
	 	} else if (isTiming == BETWEEN_CONTRACTION) {
	 	    dto.setBetweenContractionTime(dto.getBetweenContractionTime()+1000);
	 	    uicontroller.refreshBetweenContractionTimer(dto);
	 	}
	 }
	 
	 class TimeMover extends TimerTask {
	 	  public void run(){
	 	    advanceTime();
	 	  }
	 	}
}
